package com.pvdnc.tapkit.chat.chat.client;

import android.content.Context;
import android.content.Intent;
import android.os.Parcelable;

import com.pvdnc.nsocket.log.SLog;
import com.pvdnc.tapkit.chat.MessageEntity;
import com.pvdnc.tapkit.utils.BaseLocalReceiver;
import com.pvdnc.tapkit.utils.LocalBroadcast;

public abstract class MessageReceiver extends BaseLocalReceiver {
    private static final SLog LOG=new SLog(MessageReceiver.class);

    public static final String ACTION ="message.received";
    public static final String EXTRA_MESSAGE_ENTITY="message_entity";

    public MessageReceiver() {
        super(ACTION);
    }

    public static void broadcast(MessageEntity entity){
        Intent intent=new Intent();
        intent.setAction(ACTION);
        intent.putExtra(EXTRA_MESSAGE_ENTITY,entity);
        LocalBroadcast.getInstance().send(intent);
    }

    private static MessageEntity getEntity(Intent intent){
        Parcelable parcelable=intent.getParcelableExtra(EXTRA_MESSAGE_ENTITY);
        if(!(parcelable instanceof MessageEntity)){
            LOG.e("parcelable:"+parcelable+" is not a MessageEntity");
            return null;
        }
        return (MessageEntity)parcelable;
    }

    @Override
    public final void onReceive(Context context, Intent intent) {
        MessageEntity entity=getEntity(intent);
        if(entity!=null)
            onReceive(context,entity);
    }

    public abstract void onReceive(Context context,MessageEntity entity);
}
